﻿namespace BlackHole
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Web.UI.WebControls;
    using BlackHole.DAO;
    using NPOI.HSSF.UserModel;

    /// <summary>
    /// 数据导入
    /// </summary>
    public partial class DataImport : System.Web.UI.Page
    {
        /// <summary>
        /// 需要导入的产品信息
        /// </summary>
        private List<ImportRecord> records = new List<ImportRecord>();

        /// <summary>
        /// 初始化控件信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.RenderUI();
            }
        }

        /// <summary>
        /// 初始化控件 填充区县信息
        /// </summary>
        protected void RenderUI()
        {
            foreach (District d in Utility.GetAllDistricts())
            {
                this.comboDistricts.Items.Add(new ListItem(d.DistrictName, d.Id.ToString()));
            }
        }

        /// <summary>
        /// 上传待导入产品数据文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            int ownerId = 0;
            int.TryParse(this.comboOwners.SelectedValue, out ownerId);

            if (ownerId > 0)
            {
                if (this.Uploader.PostedFile.ContentLength != 0)
                {
                    try
                    {
                        string destDir = Server.MapPath("./Upload/");
                        this.Uploader.SaveAs(destDir + "up.xls");
                        this.btnInsert.Enabled = this.VaildateImportData(destDir + "up.xls");
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }

            this.panelVaildate.Visible = true;
            ViewState["ImportRecords"] = this.records;
        }

        /// <summary>
        /// 事件 更改区县
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ComboDistricts_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.comboOwners.Items.Clear();
            foreach (Owner o in Utility.GetOwnersByDistrictId(int.Parse(this.comboDistricts.SelectedValue)))
            {
                this.comboOwners.Items.Add(new ListItem(o.OwnerName, o.Id.ToString()));
            }

            this.panelUpload.Visible = true;
        }

        /// <summary>
        /// 校验数据能否插入
        /// </summary>
        /// <param name="xlsFilePath">数据文件路径</param>
        /// <returns>导入标志</returns>
        protected bool VaildateImportData(string xlsFilePath)
        {
            bool ret = true;
            int totalCount = 0, errCount = 0;
            List<District> districts = new List<District>();
            List<Owner> owners = new List<Owner>();
            List<Device> devices = new List<Device>();
            List<Fault> faults = new List<Fault>();
            devices = Utility.GetAllDevices();
            districts = Utility.GetAllDistricts();

            try
            {
                /////read the xls file
                FileStream fs = new FileStream(xlsFilePath, FileMode.Open, FileAccess.Read);
                HSSFWorkbook workbook = new HSSFWorkbook(fs);

                /////get sheet named as 数据导入
                var sheet = workbook.GetSheet("数据导入");
                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    ImportRecord r = new ImportRecord();

                    /////convert district id from district name
                    District district = new District();
                    foreach (District d in districts)
                    {
                        if (d.DistrictName.Contains(sheet.GetRow(i).GetCell(0).ToString()))
                        {
                            district.Id = d.Id;
                        }
                    }
                    /////convert owner id from owner name
                    owners = Utility.GetOwnersByDistrictId(district.Id);
                    foreach (Owner o in owners)
                    {
                        if (o.OwnerName.Contains(sheet.GetRow(i).GetCell(1).ToString()))
                        {
                            r.OwnerId = o.Id;
                        }
                    }
                    /////convert device id from devicename 
                    foreach (Device d in devices)
                    {
                        if (d.DeviceName.Contains(sheet.GetRow(i).GetCell(2).ToString()))
                        {
                            r.ProductDeviceId = d.Id;
                        }
                    }

                    /////get product information
                    r.ProductSerialNO = sheet.GetRow(i).GetCell(3).ToString();
                    r.ProductPsamNO = sheet.GetRow(i).GetCell(4) == null ? string.Empty : sheet.GetRow(i).GetCell(4).ToString();
                    r.ProductRomVersion = sheet.GetRow(i).GetCell(5) == null ? string.Empty : sheet.GetRow(i).GetCell(5).ToString();

                    /////get record information
                    /////fill faults by device ID
                    faults = Utility.GetFaultsByDeviceId(r.ProductDeviceId);
                    /////convert fault id from fault name
                    foreach (Fault f in faults)
                    {
                        if (f.FaultName.Contains(sheet.GetRow(i).GetCell(6).ToString()))
                        {
                            r.RequestFaultId = f.Id;
                        }
                    }

                    foreach (Fault f in faults)
                    {
                        if (f.FaultName.Contains(sheet.GetRow(i).GetCell(7).ToString()))
                        {
                            r.RealFaultId = f.Id;
                        }
                    }

                    r.RepairMethod = sheet.GetRow(i).GetCell(8) == null ? string.Empty : sheet.GetRow(i).GetCell(8).ToString();
                    r.RepairGear = sheet.GetRow(i).GetCell(9) == null ? string.Empty : sheet.GetRow(i).GetCell(9).ToString();

                    /////determind is import as record
                    if (r.RequestFaultId != 0 &&
                        r.RealFaultId != 0 &&
                        r.RepairMethod.Length != 0 &&
                        r.RepairGear.Length != 0)
                    {
                        r.IsRecord = true;
                    }
                    /////check product import succeed
                    if (Utility.CheckProdcutImport(ref r))
                    {
                        r.IsImportable = true;
                    }
                    else
                    {
                        /////check record import succeed
                        r.IsImportable = false;
                        errCount++;
                    }

                    if (r.ProductSerialNO.Length > 0)
                    {
                        this.records.Add(r);
                        totalCount++;
                    }
                }
            }
            catch (NPOI.OldFileFormatException)
            {
                throw;
            }

            this.lblStats.Text = "总计： " + totalCount.ToString() + " 冲突: " + errCount.ToString();

            this.dataProducts.DataSource = this.records;
            this.dataProducts.DataBind();

            return ret;
        }

        /// <summary>
        /// 事件 更改强制更新复选框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ChkForce_CheckedChanged(object sender, EventArgs e)
        {
            this.btnInsert.Enabled = this.chkForce.Checked;
        }

        /// <summary>
        /// 事件 插入数据按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnInsert_Click(object sender, EventArgs e)
        {
            bool ret;
            int count = 0;
            this.records = (List<ImportRecord>)ViewState["ImportRecords"];
            List<ImportRecord> errorlist = new List<ImportRecord>();
            foreach (ImportRecord r in this.records)
            {
                if (r.IsImportable == false)
                {
                    continue;
                }
                /////修完的直接出库 
                if (r.IsRecord)
                {
                    ret = Utility.ProductRepair(r.ProductId, r.RequestFaultId, r.RealFaultId, r.RepairMethod, r.RepairGear);
                    Utility.ProductCheckOut(r.ProductId);
                }
                else
                {
                    ret = Utility.ProductAddNew(r.ProductDeviceId, r.OwnerId, r.ProductSerialNO, r.ProductPsamNO, r.ProductRomVersion);
                }

                if (ret)
                {
                    count++;
                }
                else
                {
                    errorlist.Add(r);
                }
            }

            this.lblStats.Text = "导入完成 共 " + count.ToString();
            this.dataProducts.DataSource = errorlist;
            this.dataProducts.DataBind();
        }
    }
}